package servlet.rool;

import net.sf.json.JSONObject;
import pojo.Menu;
import pojo.RoMess;
import pojo.Role;
import service.MenuService;
import service.RoMessService;
import service.RoleService;
import service.impl.MenuServiceImpl;
import service.impl.RoMessServiceImpl;
import service.impl.RoleServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * 修改角色的servlet
 */
@WebServlet(value = "/RoleUpdateServlet")
public class RoleUpdateServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        String id=request.getParameter("ID");
        String desc=request.getParameter("desc");
        String rool=request.getParameter("rool");
        RoleService rs=new RoleServiceImpl();
        Role role=new Role();
        role.setRoId(Integer.parseInt(id));
        role.setRoDesc(desc);
        role.setRoRool(rool);
        int bo=rs.modifRole(role);
        RoMessService rms=new RoMessServiceImpl();
        int bo2=rms.deleRmass(Integer.parseInt(id));
        MenuService ms=new MenuServiceImpl();
        List<Menu> menus=ms.queryMenu();
        int bo3=0;
        if(bo2>0) {
            for (Menu menu : menus) {
                String menuId = request.getParameter(menu.getMeName());
                if (menuId != null && menuId != "") {
                    RoMess roMess=new RoMess();
                    roMess.setRoleId(Integer.parseInt(id));
                    roMess.setMenuId(Integer.parseInt(menuId));
                    bo3 = rms.inseRmass(roMess);
                }
            }
        }

        JSONObject json=new JSONObject();

        if(bo>0 && bo2>0 && bo3>0){
            json.put("message","修改成功");
        }else{
            json.put("message","修改失败");
        }

        PrintWriter out = response.getWriter();
        out.print(json);
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
        doGet(request, response);
    }
}
